package com.chinacoal.microservice.impl.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.chinacoal.microservice.impl.service.CCIPTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.chinacoal.microservice.api.WorkflowClient;
import com.chinacoal.microservice.api.model.ApproveTaskParam;
import com.chinacoal.microservice.api.model.entity.ApproveCallBackEntity;
import com.chinacoal.microservice.exception.MessageException;
import com.chinacoal.microservice.impl.mapper.ApproveCallBackMapper;
import com.chinacoal.microservice.impl.mapper.ForeignSystemTaskMapper;
import com.chinacoal.microservice.impl.service.ForeignSystemTaskService;
import com.chinacoal.microservice.model.wofkflow.entity.InstanceEntity;
import com.chinacoal.microservice.model.wofkflow.resource.WorkflowVar;
import com.chinacoal.microservice.util.result.CodeMsg;
import com.chinacoal.microservice.util.result.Result;

@Service
public class ForeignSystemTaskServiceImpl implements ForeignSystemTaskService {

    @Autowired
    private WorkflowClient workflowClient;
    @Autowired(required = false)
    private ForeignSystemTaskMapper foreignSystemTaskMapper;
    @Autowired(required = false)
    private ApproveCallBackMapper approveCallBackMapper;

    @Autowired
    private CCIPTaskService ccipTaskService;

    @Override
    public Result<Object> approveAndUpdateBusiness(ApproveTaskParam approveTaskParam) throws Exception {
        System.out.println("审批参数：" + approveTaskParam.toString() + "opcode:" + approveTaskParam.getOpcode());

        // 基础参数
        String sysCode = approveTaskParam.getSysCode();
        String bizCode = approveTaskParam.getBizCode();
        String sysTaskId = approveTaskParam.getSysTaskId();
        String businessId = approveTaskParam.getBusinessId();
        String opcode = approveTaskParam.getOpcode();

        // 获取流程配置信息
        List<ApproveCallBackEntity> approveCallBackList = approveCallBackMapper.selectApproveCallBackByBiz(sysCode, bizCode);
        if (approveCallBackList == null || approveCallBackList.size() != 1) {
            return Result.error(CodeMsg.EXECUTE_ERROR.fillArgs("流程回调配置信息有误"));
        }
        ApproveCallBackEntity approveCallBackEntity = approveCallBackList.get(0);

        // 非撤回流程需要设置待办Id
        if (!WorkflowVar.APPROVE_RECALL.equals(approveTaskParam.getOpcode())) {
            approveTaskParam.setTaskId(Long.valueOf(sysTaskId));
        }

        // 执行流程审批处理
        Result<InstanceEntity> approveResult = workflowClient.completeTask(approveTaskParam);
        if (approveResult.getCode() != 10000) {
            throw new MessageException(approveResult.getMsg());
        }
        InstanceEntity instanceEntity = approveResult.getData();

        // 修改业务状态
        String callbackMode = approveCallBackEntity.getCallbackMode();
        System.out.println("callbackMode:" + callbackMode);

        if ("1".equals(callbackMode)) { // 不执行回调

        } else if ("2".equals(callbackMode)) { // 执行本地回调处理
            String bizTabName = approveCallBackEntity.getBizTabName();
            String tabPrimaryKey = approveCallBackEntity.getTabPrimaryKey();
            String currentState = instanceEntity.getCurrentState();
            Long instanceId = instanceEntity.getInstanceId();
            String status = null;
            String statusName = null;

            if (StringUtils.isEmpty(bizTabName) || StringUtils.isEmpty(tabPrimaryKey)) {
                return Result.error(CodeMsg.EXECUTE_ERROR.fillArgs("审批成功，修改业务状态失败，原因：本地回调时配置有误"));
            } else if (WorkflowVar.APPROVE_REJECTED.equals(opcode)) {

                status = WorkflowVar.APPROVE_STATUS_REJECTED_CODE;
                statusName = WorkflowVar.APPROVE_REJECTED_NAME;
            } else if (WorkflowVar.APPROVE_RECALL.equals(opcode)) {

                status = WorkflowVar.APPROVE_STATUS_RECALL_CODE;
                statusName = WorkflowVar.APPROVE_RECALL_NAME;
            } else if (WorkflowVar.APPROVE_AGREED.equals(opcode) && "7".equals(currentState)) {

                status = WorkflowVar.APPROVE_STATUS_AGREED_CODE;
                statusName = WorkflowVar.APPROVE_AGREED_NAME;
            } else {
                status = WorkflowVar.APPROVE_STATUS_AGREED_CODE;
                statusName = WorkflowVar.APPROVE_STATUS_RUN_NAME;
            }
            // 更新单据业务状态
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("bizTabName", bizTabName);
            param.put("tabPrimaryKey", tabPrimaryKey);
            param.put("status", status);
            param.put("statusName", statusName);
            param.put("instanceId", instanceId);
            param.put("businessId", businessId);

            foreignSystemTaskMapper.updateBusiness(param);

        } else if ("3".equals(callbackMode)) { // 执行远程回调处理

            if (WorkflowVar.APPROVE_AGREED.equals(opcode)) { // 同意

                ccipTaskService.approve(businessId, bizCode, approveTaskParam);
            } else if (WorkflowVar.APPROVE_REJECTED.equals(opcode)) { // 驳回

                ccipTaskService.approveDisagree(businessId, bizCode, approveTaskParam);
            } else {
            }

        } else {
            return Result.error(CodeMsg.EXECUTE_ERROR.fillArgs("审批成功，修改业务状态失败，原因：无法识别的回调模式"));
        }

        // 返回值处理
        if (!WorkflowVar.APPROVE_RECALL.equals(approveTaskParam.getOpcode())) {
            return Result.success("审批成功");
        } else {
            return Result.success("撤回成功");
        }

    }

}
